package com.android.baselibrary.video

import android.media.MediaMetadataRetriever

object VideoExt {
    fun getVideoInfo(path: String): VideoInfo {
        val metadataRetriever = MediaMetadataRetriever()
        metadataRetriever.setDataSource(path)
        val width =
            metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
        val height =
            metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
        var widthInt = if (width.isNullOrEmpty()) 0 else width.toInt()
        var heightInt = if (height.isNullOrEmpty()) 0 else height.toInt()
        val rotation = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)
        val duration: String? = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
        var videoWidth = widthInt
        var videoHeight = heightInt
        rotation?.let {
            if ("90" == it || "270" == it) {
                videoWidth = heightInt
                videoHeight = widthInt
            }
        }
        return VideoInfo(
            path,
            rotation?.toIntOrNull() ?: 0,
            videoWidth,
            videoHeight,
            duration?.toIntOrNull() ?: 0
        )
    }
}